package com.sunfeng.chap5;

import java.awt.*;
import java.io.IOException;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.TimeUnit;

public class Test11_1 {
    public static void main(String[] args) throws IOException, InterruptedException {
        Path path = Paths.get("C:\\abc\\a.txt");
        AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
        System.out.println(System.currentTimeMillis());
        channel.lock(0, 3, false, "我是附加值", new CompletionHandler<FileLock, String>() {
            @Override
            public void completed(FileLock result, String attachment) {
                try {
                    TimeUnit.SECONDS.sleep(9);
                    result.release();
                    System.out.println(System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, String attachment) {
                System.out.println(attachment);
                System.out.println(exc.getMessage());
            }
        });
        System.out.println(System.currentTimeMillis());
        TimeUnit.SECONDS.sleep(10);
        channel.close();
    }
}
